div<!-- 查看详情  -->
<script setup lang='ts'>
import type { VxeGridInstance, VxeGridListeners } from 'vxe-table'
import type { TabsPaneContext } from 'element-plus'
import { auditCompany, getCompanyById } from '@fl/api/joint-api'
import ButtonItem from '@fl/components/button-item.vue'
import { useAesDecrypt } from '@fl/hooks/web/useCrypt'
import { ElButton, ElCard, ElCol, ElForm, ElFormItem, ElRow } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref, toRefs, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@fl/store/modules/user'

import { useDicts } from '../hooks/use-dicts'
import { useTable } from './hooks/use-table'
// import viewItem from './view.vue'

const props = withDefaults(defineProps<{
    modelValue: boolean
    showId?: string
}>(), {

})

const emits = defineEmits(['update:modelValue', 'confirm', 'goto'])

const { useDict } = useDicts()
const router = useRouter()
const isLoading = ref(true)
const userStore = useUserStore()
const isAdmin = ref<boolean>(userStore.getUserInfo?.userFlag === '1')
const backShow = ref<boolean>(userStore.getUserInfo?.userStep !== '3')
const { showId } = toRefs(props)
console.log('🚀 ~ showId:', showId)

const initialDetail = {
    id: '',
    companyName: '', // 公司名称
    companyAbbreviation: '', // 公司简称
    companyCode: '', // 统一信用代码
    companyPhone: '', // 企业联系电话
    legalName: '', // 企业法人
    legalIdCard: '',
    idCardBack: '', // 企业法人身份证（反）
    idCardFront: '', // 企业法人身份证（正）
    registeredAddress: '', // 企业注册地
    businessImg: '',
    auditStatus: '',
}
const detail = ref(cloneDeep(initialDetail))

const show = ref(false)

const activeName = ref('area')

const { appGridOptions, gridOptions } = useTable()
const xGrid = ref<VxeGridInstance<any>>()
const showPreview = ref(false)
const srcList = ref<string[]>([])

const showPic = (url: string) => {
    console.log("🚀 ~ showPic ~ url:", url)
    srcList.value = [url]
    showPreview.value = true
}

function handleClick(tab: TabsPaneContext, event: Event) {
    console.log(tab, event)
    //     activeName.value = String(tab?.paneName) || ''
    //     toggleGridOptions(String(tab?.paneName))
    //     if (tab.paneName === 'area') {
    //         gridOptions.data = detail.value?.companyAreaAssociationList ?? []
    //     }
    //     else {
    //         gridOptions.data = detail.value?.companyBusinessAssociationList ?? []
    //     }
}

const gridEvents: VxeGridListeners<any> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
    },
}

function getAreaStr(row) {
    return [row.provinceName, row.cityName, row.areaName].filter(Boolean).join(',')
}

function onSubmit() {
    // router.push(`/joint/business-management/add-enterprise?id=${detail.value.id}`)
    emits('goto', 'edit')
}

function goToList() {
    emits('confirm')
    emits('goto', 'list')
    // router.push(`/joint/business-management/company-org`)
}

async function getData() {
    getDetail()
}
function getDetail() {
    getCompanyById(String(showId.value)).then((res: any) => {
        // console.log('🚀 ~ getCompanyById ~ res:', res)
        if (res?.companyCode) {
            detail.value = res
            isLoading.value = false
        }
        gridOptions.data = res?.companyAreaAssociationList ?? []
        appGridOptions.data = res?.companyCardAssociationList?.filter((item: any) => item.openFlag === '1') ?? []
    })
}

const { isPending: auditLoading, mutateAsync: runAudit } = useMutation({
    mutationFn: (data: any) => auditCompany(data),
    onSuccess: async (data) => {
        console.log('🚀 ~ addCompany ~ data:', data)
        ElMessage.success('保存成功')
        setTimeout(() => {
            goToList()
        }, 1000)
    },
})

function audit(status: number) {
    runAudit({
        companyId: detail.value.id,
        auditStatus: String(status),
    })
}

watch(showId, (val: any) => {
    if (val) {
        console.log('🚀 ~ watch ~ val:', val)
        getData()
    }
}, {
    deep: true,
    immediate: true,
})
</script>

<template>
    <ElCard class="mb-20">
        <ElRow class="flex justify-between">
            <ElButton @click="goToList" v-if="isAdmin || backShow">
                返回列表
            </ElButton>
        </ElRow>

        <div class="info-title">
            企业注册信息
        </div>

        <el-skeleton v-if="isLoading" animated />

        <ElForm v-else :model="detail" label-width="auto">
            <div class="company-info mb-20 p-10">
                <ElRow :gutter="20" class="border-1 border-gray-300 border-solid">
                    <!-- <ElCol :span="8">
                    <div class='info-label'>企业号</div><div class='info-msg'>
                        {{ detail.enterpriseId }}
                    </div>
                </ElCol> -->

                    <ElCol :span="8">
                        <div class='info-label'>企业名称</div>
                        <div class='info-msg'>
                            {{ detail.companyName }}
                        </div>
                    </ElCol>

                    <ElCol :span="8">
                        <div class='info-label'>企业简称</div>
                        <div class='info-msg'>
                            {{ detail.companyAbbreviation }}
                        </div>
                    </ElCol>

                    <ElCol :span="8">
                        <div class='info-label'>统一社会信用代码</div>
                        <div class='info-msg'>
                            {{ detail.companyCode }}
                        </div>
                    </ElCol>

                    <ElCol :span="8">
                        <div class='info-label'>企业注册地址</div>
                        <div class='info-msg'>
                            {{ detail.registeredAddress }}
                        </div>
                    </ElCol>
                    <ElCol :span="8">
                        <div class='info-label'>企业联系电话</div>
                        <div class='info-msg'>
                            {{ detail.companyPhone }}
                        </div>
                    </ElCol>

                    <ElCol :span="8">
                        <div class='info-label'>审核状态</div>
                        <div class='info-msg'>
                            <el-tag :type="detail.auditStatus === '2' ? 'success' : 'info'">
                                {{ useDict('companyAuditStatus', detail.auditStatus) }}
                            </el-tag>
                        </div>
                    </ElCol>

                    <ElCol :span="8">
                        <div class='info-label'>企业法人</div>
                        <div class='info-msg'>
                            {{ detail.legalName }}
                        </div>
                    </ElCol>

                    <ElCol :span="16">
                        <div class='info-label'>法人证件号码</div>
                        <div class='info-msg'>
                            {{ useAesDecrypt(detail.legalIdCard) }}
                        </div>
                    </ElCol>
                    
                    <ElCol :span="8">
                        <div class='info-label'>营业执照</div>
                        <div class='info-msg'>

                            <el-button v-if="detail.idCardBack" link type="primary"
                                @click="showPic(detail.businessImg)">
                                查看图片
                            </el-button>
                        </div>
                    </ElCol>

                    <ElCol :span="8">
                        <div class='info-label'>企业法人身份证(正面)</div>
                        <div class='info-msg'>

                            <el-button v-if="detail.idCardBack" link type="primary"
                                @click="showPic(detail.idCardFront)">
                                查看图片
                            </el-button>
                        </div>
                    </ElCol>

                    <ElCol :span="8">
                        <div class='info-label'>企业法人身份证(反面)</div>
                        <div class='info-msg'>
                            <el-button v-if="detail.idCardBack" link type="primary" @click="showPic(detail.idCardBack)">
                                查看图片
                            </el-button>
                            
                        </div>
                    </ElCol>
                </ElRow>
                <el-image-viewer v-if="showPreview" :url-list="srcList" show-progress
                    @close="showPreview = false" />
            </div>
            <div class="mgt-20">
                <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                    <el-tab-pane label="负责区域" name="area">
                        <!-- 负责区域 -->
                        <!-- 列表 -->
                        <vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvents">
                            <template #area="{ row }">
                                {{ getAreaStr(row) }}
                            </template>

                            <template #createTime="{ row }">
                                {{ row.createTime }}
                            </template>
                        </vxe-grid>
                    </el-tab-pane>

                    <el-tab-pane label="开通应用" name="app">
                        <!-- 开通应用 -->
                        <!-- 列表 -->
                        <vxe-grid ref="xGrid" v-bind="appGridOptions" v-on="gridEvents" />
                    </el-tab-pane>
                </el-tabs>
            </div>
        </ElForm>

        <div v-if="isAdmin && detail.auditStatus === '1'" style="text-align: center;" class="mb20 mt60">
            <ElButton class="mx40" :loading="auditLoading" @click="audit(3)">
                驳回
            </ElButton>

            <ElButton type="primary" class="mx40" :loading="auditLoading" @click="audit(2)">
                审批通过
            </ElButton>
        </div>

        <div v-else style="text-align: center;margin-top: 20px;">
            <ElButton v-if="!isAdmin && detail.auditStatus === '1'" type="primary" @click="onSubmit">
                编辑
            </ElButton>

            <ElButton @click="goToList" v-if="isAdmin || backShow">
                返回列表
            </ElButton>
        </div>
    </ElCard>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 60px;
}

.box {
    width: 120px;
    height: 120px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.el-col{
    border: 1px solid #E5E6EB;
    padding: 0 !important;
    display: flex;
    height: 48px;
    line-height: 48px;

    .info-label {
        padding-left: 10px;
        width: 160px;
        background-color: #F7F8FA;
    }

    .info-msg {
        padding-left: 10px;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
</style>
